import {Page} from '@/base/Page';
import {deleteAccount, getAccountList} from '@/base/api/AccountApi';
import {Account} from '@/base/model/Account';
import {isEmpty} from '@/base/util/Strings';

class Form {
  userName = '';
  phone = '';
  email = '';
  createBegin = '';
  createEnd = '';
  roleId = '';
  date = [];
  companyId = [];
  type = 'MANAGE';
}

export class ListBloc {
  isShowPsdModal = false;
  accountId = 0;
  form = new Form();

  paged: Page<Account> = new Page<Account>([], 0, 1, 15, 0, []);
  loading = false;

  load(pageIndex: number, pageSize: number) {
    if (!isEmpty(this.form.date) && !isEmpty(String(this.form.date[0]))) {
      // @ts-ignore
      this.form.createBegin = this.form.date[0].getTime() || '';
      // @ts-ignore
      this.form.createEnd = this.form.date[1].getTime() + 24 * 60 * 60 * 1000 || '';
    } else {
      this.form.createBegin = '';
      this.form.createEnd = '';
    }
    this.loading = true;
    return getAccountList({
      pageIndex,
      pageSize,
      userName: this.form.userName,
      phone: this.form.phone,
      email: this.form.email,
      createBegin: this.form.createBegin,
      createEnd: this.form.createEnd,
      companyId: this.form.companyId,
      roleId: this.form.roleId,
      type:this.form.type
    }).then((res) => {
      this.paged = res.data;
    }).finally(() => {
      this.loading = false;
    });
  }

  removeItem(dateItem: Account) {
    this.loading = true;
    return deleteAccount(dateItem.id)
      .finally(() => {
        this.loading = false;
      });
  }

  reset() {
    this.form = new Form();
    this.paged.pageIndex = 1;
    this.paged.pageSize = 15;
    this.load(this.paged.pageIndex, this.paged.pageSize);
  }

  getCompanyName(companyId: number) {
    const item = this.paged.extras.find(x => x.id === companyId);
    return item == null ? '' : item.name;
  }

  getRoleName(arr: Array<string>) {
    return this.paged.extras.filter(x => arr.some(j => j === x.id.toString())).map(x => x.name).join(', ') || '';
  }

  changePsdModal(id: number) {
    this.isShowPsdModal = true;
    this.accountId = id;
  }

  savePwdModal() {
    this.isShowPsdModal = false;
    this.load(this.paged.pageIndex, this.paged.pageSize);
  }
}
